package com.ali.service.impl;

import com.ali.common.Response;
import com.ali.common.ServerUrl;
import com.ali.dao.OrderMapper;
import com.ali.dto.OrderInfo;
import com.ali.dto.PayInfo;
import com.ali.entity.Order;
import com.ali.service.OrderService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private DiscoveryClient discoveryClient;

    @Override
    public Response<OrderInfo> query(Map<String, Object> param) {
        String id = (String) param.get("id");
        Order order = orderMapper.selectById(id);
        OrderInfo orderInfo = new OrderInfo();
        BeanUtils.copyProperties(order, orderInfo);

        //内部服务调用
        Response<List<PayInfo>> payResponse = restTemplate.getForObject(ServerUrl.PAY_URL + "/pay/query?orderid={orderid}", Response.class, id);
        orderInfo.setPayInfos(payResponse.getData());
        return Response.success(orderInfo);
    }

    @Override
    public Response<Map<String, Object>> getServiceInfo(@RequestParam Map<String, Object> param) {
        Map<String, Object> map = new HashMap<>();

        List<String> services = discoveryClient.getServices();
        map.put("services", services);

        Object serviceId = param.get("serviceid");
        if (serviceId != null) {
            List<ServiceInstance> serviceInstances = discoveryClient.getInstances((String) serviceId);
            map.put("serviceInstances", serviceInstances);
        }

        return Response.success(map);
    }

    @Override
    public Response<String> getConfigInfo(String info) {
        return Response.success(info);
    }
}
